package models;

public class Tree {
    public String[] dataString;

    public TreeNode creatTreeNode() {
        if (dataString.length <= 0) {
            return null;
        }
        TreeNode[] NodeArray = new TreeNode[dataString.length];

        for (int i = 0; i <= dataString.length - 1; i++) {
            if (!dataString[i].equals("#")) {
                // 这里是个坑，如果不判断就 new, 导致子节点重新创建，爷孙关系就断了, A -->B, C---->D, C
                // 是重新创建的节点
                if (NodeArray[i] == null) {
                    NodeArray[i] = new TreeNode(
                            Integer.valueOf(dataString[i]));
                }

                int idx = 2 * i + 1;
                if (idx <= dataString.length - 1
                        && !dataString[i].equals("#")) {
                    NodeArray[idx] = new TreeNode(
                            Integer.valueOf(dataString[idx]));
                    NodeArray[i].left = NodeArray[idx];
                } else {
                    NodeArray[i].left = null;
                }

                idx++;
                if (idx <= dataString.length - 1
                        && !dataString[i].equals("#")) {
                    NodeArray[idx] = new TreeNode(
                            Integer.valueOf(dataString[idx]));
                    NodeArray[i].right = NodeArray[idx];
                } else {
                    NodeArray[i].right = null;
                }
            }
        }
        return NodeArray[0];
    }

    public void preOrderTravel(TreeNode node) {
        System.out.print(node.val + " ");
        if (node.left != null) {
            preOrderTravel(node.left);
        }
        if (node.right != null) {
            preOrderTravel(node.right);
        }
    }
    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        String temp = "hello sfd worldsdf ";
        System.out.println(temp);

        Tree mytree = new Tree();
        // case 1
        // mytree.dataString = "392##57";
        // case 2
        mytree.dataString = new String[]{"1","5","2","8","9","3"};
        TreeNode root = mytree.creatTreeNode();

        // 先序遍历
        mytree.preOrderTravel(root);
    }
}

